/** ###################################################################
**     Filename  : gear.C
**     Project   : Motologger_v2
**     Processor : MC9S12XD256BMFU
**     Compiler  : CodeWarrior HCS12X C Compiler
**     Date/Time : 11/14/2009, 6:26 PM
**     Contents  :
**         User source code
**
**     (c) Copyright UNIS, spol. s r.o. 1997-2007
**     UNIS, spol. s r.o.
**     Jundrovska 33
**     624 00 Brno
**     Czech Republic
**     http      : www.processorexpert.com
**     mail      : info@processorexpert.com
** ###################################################################*/

/* MODULE gear */
#include "gear.h"
#include "Vbat_Gear_ADC.h"

#define GEAR_NUM2AVG 8
unsigned short gear_vals[GEAR_NUM2AVG];
unsigned short gear_adc;
 
#define GEARLERR 2000 //open circuit/neutral
#define GEAR1THR 700
#define GEAR2THR 525
#define GEAR3THR 1850
#define GEAR4THR 1655
#define GEAR5THR 1300
#define GEAR6THR 995

#define GEAR_ADC_CHAN 1

#define GEAR_AVG 0

unsigned short Gear_GetVal(void){

#if GEAR_AVG
  unsigned short gearAvgADCVal=0;  
  unsigned char avgIndex;
  
  for(avgIndex = 0;avgIndex<GEAR_NUM2AVG;avgIndex++){
		gearAvgADCVal+=gear_vals[avgIndex];  		
  }
	gear_adc=gearAvgADCVal/GEAR_NUM2AVG;
#endif

  if(gear_adc>GEARLERR){
    return 0;
  }else if(gear_adc<(GEAR1THR +100) && gear_adc >(GEAR1THR -50) ){
    return 1;
  }else if(gear_adc<(GEAR2THR +100) && gear_adc >(GEAR2THR -100)){
    return 2;
  }else if(gear_adc<(GEAR3THR +30) && gear_adc >(GEAR3THR -30)){
    return 3;
  }else if(gear_adc<(GEAR4THR +30) && gear_adc >(GEAR4THR -30)){
    return 4;
  }else if(gear_adc<(GEAR5THR +30) && gear_adc >(GEAR5THR -30)){
    return 5;
  }else if(gear_adc<(GEAR6THR +30) && gear_adc >(GEAR6THR -30)){
    return 6;
  }else{
    return 0;
  }
}


void Gear_Update(void){

#if GEAR_AVG
  
  static unsigned char avgIndex;
  Vbat_Gear_ADC_GetChanValue16((byte)GEAR_ADC_CHAN, &gear_vals[avgIndex%GEAR_NUM2AVG]);
  avgIndex++;
  
#else

	Vbat_Gear_ADC_GetChanValue16((byte)GEAR_ADC_CHAN, &gear_adc);
	
#endif  

}
 

/* END gear */
